package com.yc.jpyy.mobile.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.config.Config;


@Controller
@RequestMapping(value = "/file")
public class FileUploadController {
	private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);

	/**
	 * 添加教练或驾校评价
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/fileUpload", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	public @ResponseBody String fileUpload(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");

		try {
			LocalDateTime now = LocalDateTime.now();
			String year = String.valueOf(now.getYear());// 年
			String month = String.valueOf(now.getMonthValue());// 月
			String day = String.valueOf(now.getDayOfMonth());// 日
			String filePath = Config.getFileLog() + year + "\\" + month + "\\" + day + "\\";
	        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
	        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
	                request.getSession().getServletContext());
	        //检查form中是否有enctype="multipart/form-data"
	        if(multipartResolver.isMultipart(request))
	        {
	            //将request变成多部分request
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
	            MultipartFile file = multiRequest.getFile("file");
	            //获取multiRequest 中所有的文件名
	            if(file != null)
                {
                    File files = new File(filePath);
                    //如果保存文件的地址不存在，就先创建目录
                    if(!files.exists()){
                        files.mkdirs();
                    }
                    String path = filePath + request.getParameter("fileName") + ".txt";
                    //上传
                    file.transferTo(new File(path));
                }

	        }	
		} catch (Exception e) {
			logger.info("fileUpload："+ e.toString());
			response.setErrorcode(1);
			response.setMessage("上传失败，请稍候重试！");
		} finally {
			return response.toJSON();
		}
	}
	
}
